package ru.urfc.portal.ui.client;

import java.util.ArrayList;
import java.util.List;

import com.extjs.gxt.ui.client.data.BaseLoader;
import com.extjs.gxt.ui.client.data.Loader;
import com.extjs.gxt.ui.client.data.ModelData;
import com.extjs.gxt.ui.client.event.BaseEvent;
import com.extjs.gxt.ui.client.event.BaseObservable;
import com.extjs.gxt.ui.client.event.EventType;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.event.Observable;
import com.extjs.gxt.ui.client.store.ListStore;

public class Agregator extends BaseObservable {
	List<Listener<? extends BaseEvent>> listeners = new ArrayList<Listener<? extends BaseEvent>>();
	static public EventType AGREGATED = new EventType();
	
	protected void onEvent() {
		if (isComplete()) {
			fireEvent(AGREGATED);
		}
	}

	private boolean isComplete() {
		return listeners.size() == 0;
	}

	public void listenLoaded(BaseLoader<?> loader) {
		listen(loader, Loader.Load);
	}

	public void listenLoaded(ListStore<ModelData> store) {
		listen(store.getLoader(), Loader.Load);
	}

	public void listen(final Observable observable, final EventType eventType) {
		final Listener<BaseEvent> listener = new Listener<BaseEvent>() {
			@Override
			public void handleEvent(BaseEvent event) {
				listeners.remove(this);
				observable.removeListener(eventType, this);
				onEvent();
			}			
		};
		listeners.add(listener);
		observable.addListener(eventType, listener);
	}

	/**
	 * Useful when listen empty set of {@link Observable}'s
	 */
	public void check() {
		onEvent();
	}
	
}